package mamikeji.liaowa.ui.activity.right;

import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.util.TypedValue;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import mamikeji.liaowa.R;
import mamikeji.liaowa.bean.CollectionListBean;
import mamikeji.liaowa.bean.CollectionTypeBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.BaseActivity;
import mamikeji.liaowa.ui.adapter.CollectionAdapter;
import mamikeji.liaowa.ui.fragment.favorite.ArticFragment;
import mamikeji.liaowa.ui.fragment.favorite.TopicFragment;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;

public class UserCollectionActivity extends BaseActivity {
    private static final String TAG = "UserCollectionActivity";
    private static final int TAG_CIRCLE = 1001;
    private static final int FIRST_PAGE = 0;
    private static final int SECOND_PAGE = 1;
    private List<CollectionListBean.DataEntity> dataEntityList = new ArrayList<>();
    private List<CollectionTypeBean.DataEntity> collectionTypeList = new ArrayList<>();
    private CollectionAdapter collectionAdapter;
    private MultiStateView multiStateView_collection_type;
    private TabLayout tabLayout;
    private FrameLayout mContainer;


    @Override
    protected void onStart() {
        super.onStart();
        //修改tabLayout下划线的长度
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                setIndicator(tabLayout, 50, 50);
            }
        });

        //为tabLayout加垂直线条
        LinearLayout linearLayout = (LinearLayout) tabLayout.getChildAt(0);
        linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        linearLayout.setDividerPadding(50);
        linearLayout.setDividerDrawable(ContextCompat.getDrawable(this, R.drawable.layout_divider_vertical));
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_collection);
        getBase();
        setTitleLeftBtn();
        setTitleName(R.string.user_collection_name);

//        init();

        //初始化控件
        initView();


        //初始化data
        initData();


    }

    private void initData() {

        getSupportFragmentManager().beginTransaction().replace(R.id.framelayout_container, new TopicFragment()).commit();

        //为tablayout设置监听
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()) {
                    case FIRST_PAGE:
                        getSupportFragmentManager().beginTransaction().replace(R.id.framelayout_container, new TopicFragment()).commit();
                        break;
                    case SECOND_PAGE:
                        getSupportFragmentManager().beginTransaction().replace(R.id.framelayout_container, new ArticFragment()).commit();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }


    private void initView() {

        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        mContainer = (FrameLayout) findViewById(R.id.framelayout_container);


    }


    /**
     * 修改tabLayout下划线的长度
     *
     * @param tabs
     * @param leftDip
     * @param rightDip
     */
    public void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }


    }


    /**
     * 加载布局控件
     */
    private void init() {
//        collectionAdapter = new CollectionAdapter(dataEntityList, this);
//
//        multiStateView_collection_type = (MultiStateView) findViewById(R.id.multiStateView_collection_type);
//
//        multiStateView_collection_type.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.button_error_refish)
//                .setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        multiStateView_collection_type.setViewState(MultiStateView.VIEW_STATE_LOADING);
//                        getCollectionDate();
//                    }
//                });
//
//        multiStateView_collection_type.setEmptyText(R.string.user_collection_article_type).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                startActivityForResult(new Intent(UserCollectionActivity.this , ArticleTypeActivity.class), TAG_CIRCLE);
//            }
//        });
//
//        listView_collection_data.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                Intent intent = new Intent(UserCollectionActivity.this, Article_DetailsActivity.class);
//                intent.putExtra("articleId", dataEntityList.get(i).getArticleId() + "");
//                startActivityForResult(intent, TAG_CIRCLE);
//            }
//        });

//        collectionAdapter.setOnItemClickListener(new CollectionAdapter.OnItemClickListener() {
//            @Override
//            public void onDeleteClick(int position) {
//                deleteCollection(dataEntityList.get(position).getArticleId() , position);
//            }
//        });
    }


    /**
     * 收藏数据
     */
    private void getCollectionDate() {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.COLLECTION_DATE_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.COLLECTION_DATE_CATEGORY, "0");
        formMap.put(HttpKey.COLLECTION_DATE_PAGE, "1");
        formMap.put(HttpKey.COLLECTION_DATE_PAGESIZE, "10");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.COLLECTION_DATE, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                multiStateView_collection_type.setViewState(MultiStateView.VIEW_STATE_NOINTERNET);
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        CollectionListBean collectionListBean = new Gson().fromJson(response, CollectionListBean.class);
                        if (collectionListBean.getData() != null) {
                            dataEntityList = new ArrayList<CollectionListBean.DataEntity>();
                            dataEntityList = collectionListBean.getData();

                            multiStateView_collection_type.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        } else {
                            multiStateView_collection_type.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                        }
                    } else {
                        multiStateView_collection_type.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 删除数据
     */
    private void deleteCollection(int articleId, final int position) {
        showLoading();
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.COLLECTION_ARTICLE_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.COLLECTION_ARTICLE_ARTICLEID, articleId + "");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.COLLECTION_DELETE, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i("Exception", e.getMessage());
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                hideLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        dataEntityList.remove(position);

                        collectionAdapter.setList(dataEntityList);

                        int num = ForPreference.getInt(ForContents.USER_COLLECTION);
                        //记录收藏数量
                        ForPreference.putInt(ForContents.USER_COLLECTION, --num);

                        if (dataEntityList.size() == 0) {
                            getCollectionDate();
                        }
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == TAG_CIRCLE) {
                //获取收藏数据
                getCollectionDate();
            }
        }
    }

}